/*
 * Copyright 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cloudtasks;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.appspot.api.services.taskservice.model.Task;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Main activity - requests "Hello, World" messages from the server and provides
 * a menu item to invoke the accounts activity.
 */
public class CloudTasksActivity extends Activity implements OnItemClickListener {
    /**
     * Tag for logging.
     */
    private static final String TAG = "CloudTasksActivity";

    /**
     * The current context.
     */
    private Context mContext = this;

    private final static int NEW_TASK_REQUEST = 1;
    private ListView listView;
    private View progressBar;
    private TaskAdapter adapter;
    private AsyncFetchTask task;


    /**
     * Begins the activity.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);


        setContentView(R.layout.tasklist);

        listView = (ListView) findViewById(R.id.list);
        progressBar = findViewById(R.id.title_refresh_progress);

        // get the task application to store the adapter which will act as the task storage
        // for this demo.
        TaskApplication taskApplication = (TaskApplication) getApplication();
        adapter = taskApplication.getAdapter(this);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        // Invoke the Register activity
        menu.getItem(0).setIntent(new Intent(this, AccountsActivity.class));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.menu_refresh:
			fetchTasks(-1);
			break;

		default:
			break;
		}
    	return super.onOptionsItemSelected(item);
    }



    @Override
    protected void onStart() {
        super.onStart();
        // only fetch task on start if an account has been selected
//        SharedPreferences prefs = Util.getSharedPreferences(mContext);
//        String deviceRegistrationId = prefs.getString(Util.DEVICE_REGISTRATION_ID, null);
//        if (deviceRegistrationId != null) {
        		fetchTasks(-1);
//        }
//        else {
//        		startActivity(new Intent(this,AccountsActivity.class));
//        }
    }

    public void fetchTasks(long id) {
        progressBar.setVisibility(View.VISIBLE);
        if (task != null) {
            task.cancel(true);
        }
        task = new AsyncFetchTask(this);
        task.execute(id);
    }

    public void setTasks(List<Task> tasks) {
        progressBar.setVisibility(View.GONE);
        adapter.setTasks(tasks);
        adapter.notifyDataSetChanged();
    }

    public void addTasks(List<Task> tasks) {
        progressBar.setVisibility(View.GONE);
        adapter.addTasks(tasks);
        adapter.notifyDataSetChanged();
    }

    public void onAddClick(View view) {
        Intent intent = new Intent(this, AddTaskActivity.class);
        startActivityForResult(intent, NEW_TASK_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case NEW_TASK_REQUEST:
            if (resultCode == Activity.RESULT_OK) {
                final String taskName = data.getStringExtra("task");
                final String taskDetails = data.getStringExtra("details");

                Calendar c = Calendar.getInstance();
                c.set(data.getIntExtra("year", 2011),
                        data.getIntExtra("month", 12),
                        data.getIntExtra("day", 31));
                final String dueDate = c.getTime().toString();
                
                Task newTask = new Task();
                newTask.setName(taskName);
                newTask.setNote(taskDetails);
                newTask.setDueDate(dueDate);

                new AddTaskTask(adapter, this).execute(newTask);
            }
            break;
        }
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ViewTaskActivity.class);
        intent.putExtra("position", position);
        startActivity(intent);
    }


}
